//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package kd.ec.basedata.common.update;

import java.util.*;
import java.util.stream.Collectors;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicLocaleProperty;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.property.EntryProp;
import kd.bos.entity.property.MulBasedataProp;
import kd.bos.entity.property.SubEntryProp;
import kd.bos.orm.ORM;
import kd.bos.util.StringUtils;
import kd.ec.basedata.common.utils.BillUpdateHelper;

public abstract class BillUpdateCommonOp extends AbstractOperationServicePlugIn {
    protected BillUpdateHelper updateHelper = new BillUpdateHelper();

    public BillUpdateCommonOp() {
    }

    public Boolean isEditFields(String name) {
        return name.startsWith("hc95") || "seq".equalsIgnoreCase(name);
    }

    public void initIgnoreFields(BillUpdateHelper newHelper) {
        this.updateHelper = newHelper;
    }

    public void onPreparePropertys(PreparePropertysEventArgs e) {
        MainEntityType dataEntityType = this.billEntityType;
        DataEntityPropertyCollection properties = dataEntityType.getProperties();
        Iterator var4 = properties.iterator();

        while (true) {
            while (var4.hasNext()) {
                IDataEntityProperty property = (IDataEntityProperty) var4.next();
                if (property instanceof EntryProp) {
                    EntryProp entryProp = (EntryProp) property;
                    DynamicObjectType entryType = entryProp.getDynamicCollectionItemPropertyType();
                    DataEntityPropertyCollection entryProps = entryType.getProperties();
                    Iterator var9 = entryProps.iterator();

                    while (var9.hasNext()) {
                        IDataEntityProperty prop = (IDataEntityProperty) var9.next();
                        e.getFieldKeys().add(prop.getName());
                    }
                } else {
                    e.getFieldKeys().add(property.getName());
                }
            }

            return;
        }
    }

    protected void saveDataToSource(DynamicObject dataEntity, DynamicObject source, DataEntityPropertyCollection properties, DynamicObjectType projectType) {
        Set<Object> ignoreFields = this.updateHelper.ignoreFields;
        Iterator var6 = properties.iterator();

        while (var6.hasNext()) {
            IDataEntityProperty property = (IDataEntityProperty) var6.next();
            if (property instanceof EntryProp) {
                this.handleEntry(property, source, dataEntity);
            } else if (!this.handleSomeFields(property, source, dataEntity)) {
                String name = property.getName();
                if (!name.endsWith("_id") && !ignoreFields.contains(name) && projectType.getProperty(name) != null) {
                    source.set(name, dataEntity.get(name));
                }
            }
        }

    }

    protected boolean handleSomeFields(IDataEntityProperty property, DynamicObject source, DynamicObject dataEntity) {
        String name = property.getName();
        boolean flag = false;
        DynamicObjectCollection targetCollection;
        if (property instanceof DynamicLocaleProperty) {
            DynamicObjectCollection sourceCollection = dataEntity.getDynamicObjectCollection(name);
            targetCollection = source.getDynamicObjectCollection(name);
            if (sourceCollection.isEmpty() || targetCollection.isEmpty()) {
                return true;
            }

            Map<String, String> sourceMap = (Map) sourceCollection.stream().collect(Collectors.toMap((key) -> {
                return key.getString("localeid");
            }, (value) -> {
                return value.getString("name");
            }));
            Iterator var9 = targetCollection.iterator();

            while (var9.hasNext()) {
                DynamicObject targetLocaleObject = (DynamicObject) var9.next();
                targetLocaleObject.set("name", sourceMap.get(targetLocaleObject.getString("localeid")));
            }

            flag = true;
        } else if (property instanceof MulBasedataProp) {
            DynamicObjectType projectMultiDataType = source.getDynamicObjectCollection(property.getName()).getDynamicObjectType();
            targetCollection = dataEntity.getDynamicObjectCollection(property.getName());
            DynamicObjectCollection sourceNewMultiData = this.toMultiBaseDataForDB(targetCollection, projectMultiDataType);
            source.set(property.getName(), sourceNewMultiData);
            flag = true;
        }

        return flag;
    }

    protected void handleEntry(IDataEntityProperty property, DynamicObject source, DynamicObject dataEntity) {
        EntryProp entryProp = (EntryProp) property;
        DynamicObjectType entryType = entryProp.getDynamicCollectionItemPropertyType();
        if (entryType != null) {
            DataEntityPropertyCollection entryProps = entryType.getProperties();
            DynamicObjectCollection unitProjectEntry = dataEntity.getDynamicObjectCollection(property.getName());
            DynamicObjectCollection unitProjectEntities = source.getDynamicObjectCollection(property.getName());
            this.entryAdd(unitProjectEntry, unitProjectEntities, entryProps, this.getEntryKeyByEntry(property.getName()));
        }

    }

    protected abstract String getEntryKeyByEntry(String var1);

    protected DynamicObjectCollection toMultiBaseDataForDB(DynamicObjectCollection input, DynamicObjectType dynamicObjectType) {
        DynamicObjectCollection result = new DynamicObjectCollection();
        ORM orm = ORM.create();
        Iterator var5 = input.iterator();

        while (var5.hasNext()) {
            DynamicObject object = (DynamicObject) var5.next();
            DynamicObject coodept = new DynamicObject(dynamicObjectType);
            coodept.set("pkid", orm.genLongId(dynamicObjectType));
            coodept.set("fbasedataid", object.get("fbasedataid"));
            coodept.set("fbasedataid_id", object.get("fbasedataid_id"));
            result.add(coodept);
        }

        return result;
    }

    protected void doProjectUpdateBuildingEntry(DynamicObjectCollection billEntry, DynamicObjectCollection projectEntry, DataEntityPropertyCollection entryProps) {
        if (billEntry != null && billEntry.size() >= 1) {
            List<String> sourceidLdIds = billEntry.stream().map(i -> i.getString("hc95_sourceid_ld")).collect(Collectors.toList());
            if (projectEntry != null && projectEntry.size() >= 1) {
                //处理删除
                List<DynamicObject> removeOb = new ArrayList<DynamicObject>();
                for (int i = 0; i < projectEntry.size(); i++) {
                    DynamicObject dynamicObject = projectEntry.get(i);
                    String idEn = dynamicObject.getString("id");
                    if (sourceidLdIds != null && sourceidLdIds.size() >= 1) {
                        if (!sourceidLdIds.contains(idEn)) {
                            removeOb.add(dynamicObject);
                        }
                    } else {
                        removeOb.add(dynamicObject);
                    }
                }
                if (removeOb != null && removeOb.size() >= 1) {
                    projectEntry.removeAll(removeOb);
                }
            }
            DynamicObjectType billEntryType = billEntry.getDynamicObjectType();//项目变更单
            DynamicObjectType unitProjectType = projectEntry.getDynamicObjectType();//项目
            for (int i = 0; i < billEntry.size(); i++) {
                DynamicObject rowChageEn = billEntry.get(i);
                String hc95_sourceid_ld = rowChageEn.getString("hc95_sourceid_ld");
                if (StringUtils.isNotEmpty(hc95_sourceid_ld)) {
                    Optional<DynamicObject> isCheckRow = projectEntry.stream().filter(f1 -> f1.getString("id").equalsIgnoreCase(hc95_sourceid_ld)).findFirst();
                    if (isCheckRow.isPresent()) {
                        //存在
                        DynamicObject projectEntryEditRow = isCheckRow.get();
                        doProjectEntryData(entryProps, projectEntryEditRow, unitProjectType, billEntryType, rowChageEn, true);
                    } else {
                        //不存在 新增
                        DynamicObject projectEntryNewRow = projectEntry.addNew();
                        doProjectEntryData(entryProps, projectEntryNewRow, unitProjectType, billEntryType, rowChageEn, false);
                    }
                } else {
                    //为空手动新增
                    DynamicObject projectEntryNewRow = projectEntry.addNew();
                    doProjectEntryData(entryProps, projectEntryNewRow, unitProjectType, billEntryType, rowChageEn, false);
                }
            }
        }

    }

    protected void doProjectEntryData(DataEntityPropertyCollection entryProps, DynamicObject projectBuildingEntry, DynamicObjectType unitProjectType, DynamicObjectType billEntryType, DynamicObject rowChageEn, Boolean isEdit) {
        Iterator<IDataEntityProperty> iterator = entryProps.iterator();
        while (iterator.hasNext()) {
            IDataEntityProperty prop = (IDataEntityProperty) iterator.next();
            String name = prop.getName();
            if (unitProjectType.getProperty(name) != null && billEntryType.getProperty(name) != null && isEditFields(name)) {
                if (prop instanceof SubEntryProp) {
                    //子单据体
                    SubEntryProp subEntryProp = (SubEntryProp) prop;
                    DynamicObjectType dynamicCollectionItemPropertyType = subEntryProp.getDynamicCollectionItemPropertyType();
                    DataEntityPropertyCollection subProperties = dynamicCollectionItemPropertyType.getProperties();
                    DynamicObjectCollection subChangeEdit = (DynamicObjectCollection) rowChageEn.get(prop.getName());//变更单的
                    DynamicObjectCollection subProjectEdit = (DynamicObjectCollection) projectBuildingEntry.get(prop.getName());//项目基础资料
                    doSuperProjectEntryData(subProperties, name, subChangeEdit, subProjectEdit, projectBuildingEntry);
                }else{
                    projectBuildingEntry.set(name, rowChageEn.get(name));
                }
            }
        }
    }


    protected void doProjectSubEntryData(DataEntityPropertyCollection entryProps, DynamicObject addOrEditEntryRow, DynamicObjectType targetType, DynamicObjectType sourceType, DynamicObject sourceEnRow, Boolean isEdit) {
        Iterator<IDataEntityProperty> iterator = entryProps.iterator();
        while (iterator.hasNext()) {
            IDataEntityProperty prop = (IDataEntityProperty) iterator.next();
            String name = prop.getName();
            if (targetType.getProperty(name) != null && sourceType.getProperty(name) != null && isEditFields(name)) {
                addOrEditEntryRow.set(name, sourceEnRow.get(name));
            }
        }
    }

    private void doSuperProjectEntryData(DataEntityPropertyCollection subProperties, String name, DynamicObjectCollection subChangeEdit, DynamicObjectCollection subProjectEdit,DynamicObject projectBuildingEntry) {
        if ("hc95_building_dx".equalsIgnoreCase(name) || "hc95_building_ds".equalsIgnoreCase(name)) {
            //删除
            String sourceIdKey="";
            if ("hc95_building_dx".equalsIgnoreCase(name)) {
                sourceIdKey="hc95_sourceid_dx";
            } else if ("hc95_building_ds".equalsIgnoreCase(name)) {
                sourceIdKey="hc95_sourceid_ds";
            }
            String finalSourceIdKey = sourceIdKey;
            List<String> sourceidLdIds = subChangeEdit.stream().map(i -> i.getString(finalSourceIdKey)).collect(Collectors.toList());
            if (subProjectEdit != null && subProjectEdit.size() >= 1) {
                //处理删除
                List<DynamicObject> removeOb = new ArrayList<DynamicObject>();
                for (int i = 0; i < subProjectEdit.size(); i++) {
                    DynamicObject dynamicObject = subProjectEdit.get(i);
                    String idEn = dynamicObject.getString("id");
                    if (sourceidLdIds != null && sourceidLdIds.size() >= 1) {
                        if (!sourceidLdIds.contains(idEn)) {
                            removeOb.add(dynamicObject);
                        }
                    } else {
                        removeOb.add(dynamicObject);
                    }
                }
                if (removeOb != null && removeOb.size() >= 1) {
                    subProjectEdit.removeAll(removeOb);
                }
            }

            DynamicObjectType billSubEntryType = subChangeEdit.getDynamicObjectType();//项目变更单
            DynamicObjectType unitSubProjectType = subProjectEdit.getDynamicObjectType();//项目
            for (int i = 0; i < subChangeEdit.size(); i++) {
                DynamicObject rowChageEn = subChangeEdit.get(i);
                String sourceid = "";
                if ("hc95_building_dx".equalsIgnoreCase(name)) {
                    sourceid = rowChageEn.getString("hc95_sourceid_dx");
                } else if ("hc95_building_ds".equalsIgnoreCase(name)) {
                    sourceid = rowChageEn.getString("hc95_sourceid_ds");
                }
                if (StringUtils.isNotEmpty(sourceid)) {
                    String finalSourceid = sourceid;
                    Optional<DynamicObject> isCheckRow = subProjectEdit.stream().filter(f1 -> f1.getString("id").equalsIgnoreCase(finalSourceid)).findFirst();
                    if (isCheckRow.isPresent()) {
                        //存在
                        DynamicObject projectSubEntryEditRow = isCheckRow.get();
                        doProjectSubEntryData(subProperties, projectSubEntryEditRow, unitSubProjectType, billSubEntryType, rowChageEn, true);
                    } else {
                        //不存在 新增
                        DynamicObject subEntryNewRow = subProjectEdit.addNew();
                        doProjectSubEntryData(subProperties, subEntryNewRow, unitSubProjectType, billSubEntryType, rowChageEn, false);
                    }
                } else {
                    //为空手动新增
                    DynamicObject subEntryNewRow = subProjectEdit.addNew();
                    doProjectSubEntryData(subProperties, subEntryNewRow, unitSubProjectType, billSubEntryType, rowChageEn, false);
                }
            }
            projectBuildingEntry.set(name,subProjectEdit);
        }


    }

    protected void entryAdd(DynamicObjectCollection billEntry, DynamicObjectCollection projectEntry, DataEntityPropertyCollection entryProps, String entryKey) {
        DynamicObjectType unitProjectType = projectEntry.getDynamicObjectType();
        if (unitProjectType != null) {
            String billEntityTypeName = this.billEntityType.getName();
            String unitProjectTypeName = unitProjectType.getName();
            switch (billEntityTypeName) {
                case "ecbd_projectupdate":
                    if ("hc95_building".equalsIgnoreCase(unitProjectTypeName)) {
                        doProjectUpdateBuildingEntry(billEntry, projectEntry, entryProps);
                        return;
                    }
                    break;
            }
        }
        DynamicObjectType billEntryType = billEntry.getDynamicObjectType();
        Iterator var7 = billEntry.iterator();

        while (true) {
            DynamicObject entity;
            do {
                if (!var7.hasNext()) {
                    return;
                }

                entity = (DynamicObject) var7.next();
            } while (!entity.getBoolean(entryKey));

            DynamicObject unitpro = projectEntry.addNew();
            Iterator var10 = entryProps.iterator();

            while (var10.hasNext()) {
                IDataEntityProperty prop = (IDataEntityProperty) var10.next();
                String name = prop.getName();
                if (unitProjectType.getProperty(name) != null && billEntryType.getProperty(name) != null) {
                    unitpro.set(name, entity.get(name));
                }
            }
        }
    }
}
